package com.lastcode6175.bluetoothremotecontrol

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

import androidx.compose.ui.window.Popup
import androidx.core.content.ContextCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import com.lastcode6175.bluetoothremotecontrol.ui.theme.BluetoothRemoteControlTheme
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    private var bluetoothService: BluetoothService? by mutableStateOf(null)
    private var isServiceBound by mutableStateOf(false)

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            val binder = service as BluetoothService.LocalBinder
            bluetoothService = binder.getService()
            isServiceBound = true
            Log.d("MainActivity", "Service connected")
        }

        override fun onServiceDisconnected(arg0: ComponentName) {
            isServiceBound = false
            Log.d("MainActivity", "Service disconnected")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val serviceIntent = Intent(this, BluetoothService::class.java)
        ContextCompat.startForegroundService(this, serviceIntent)
        bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE)

        setContent {
            BluetoothRemoteControlTheme {
                if (isServiceBound) {
                    RemoteControlScreen(bluetoothService as BluetoothServiceApi)
                } else {
                    Log.d("MainActivity", "Service not bound yet, showing empty screen")
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isServiceBound) {
            unbindService(serviceConnection)
            isServiceBound = false
        }
        val serviceIntent = Intent(this, BluetoothService::class.java)
        stopService(serviceIntent)
    }
}

@Composable
fun keyboardAsState(): State<Boolean> {
    val isImeVisible = WindowInsets.ime.getBottom(LocalDensity.current) > 0
    return rememberUpdatedState(isImeVisible)
}

@Composable
fun RemoteControlScreen(bluetoothService: BluetoothServiceApi?) {
    val context = LocalContext.current
    val bluetoothViewModel: BluetoothViewModel = viewModel(factory = BluetoothViewModelFactory())
    bluetoothService?.let { bluetoothViewModel.setBluetoothService(it) }
    // 蓝牙连接状态管理
    val bluetoothState by bluetoothViewModel.state.collectAsState()
    val connectedDeviceName by bluetoothViewModel.connectedDeviceName.collectAsState()
    val availableDevices by bluetoothViewModel.availableDevices.collectAsState()
    val errorMessage by bluetoothViewModel.errorMessage.collectAsState()

    val permissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestMultiplePermissions(),
        onResult = { permissions ->
            val allPermissionsGranted = permissions.values.all { it }
            if (allPermissionsGranted) {
                bluetoothViewModel.scanDevices()
            }
        }
    )

    LaunchedEffect(key1 = bluetoothViewModel) {
        bluetoothViewModel.permissionRequest.collectLatest {
            permissionLauncher.launch(it)
        }
        // 在RemoteControlScreen首次组合时检查权限
        bluetoothViewModel.checkPermissions()
    }

    // 自动重连功能
    val coroutineScope = rememberCoroutineScope()

    var selectedIndex by remember { mutableIntStateOf(-1) }
    val isGyroMouseActive = selectedIndex == 0
    val isTouchpadActive = selectedIndex == 1
    val isKeyboardActive = selectedIndex == 2
    
    // 初始化鼠标控制器
    val gyroMouseController = remember { GyroMouseController(context) }
    val touchpadController = remember { TouchpadController() }
    val scrollState = rememberScrollState()
    val focusRequester = remember { FocusRequester() }
    var inputText by remember { mutableStateOf("") }
    
    // 监听键盘可见性状态
    val isKeyboardVisible by keyboardAsState()

    // 鼠标控制模式效果
    LaunchedEffect(isGyroMouseActive) {
        if (isGyroMouseActive) {
            bluetoothViewModel.setMouseControlMode(MouseControlMode.GYRO)
            gyroMouseController.onMouseMove = { dx, dy ->
                bluetoothViewModel.sendMouseMove(dx, dy)
            }
            gyroMouseController.start()
        } else {
            gyroMouseController.stop()
            if (bluetoothViewModel.mouseControlMode.value == MouseControlMode.GYRO) {
                bluetoothViewModel.setMouseControlMode(MouseControlMode.NONE)
            }
        }
    }
    
    LaunchedEffect(isTouchpadActive) {
        if (isTouchpadActive) {
            bluetoothViewModel.setMouseControlMode(MouseControlMode.TOUCHPAD)
            touchpadController.onMouseMove = { dx, dy ->
                bluetoothViewModel.sendMouseMove(dx, dy)
            }
            touchpadController.onMouseClick = {
                bluetoothViewModel.sendMouseClick()
            }
            touchpadController.onMouseScroll = { amount ->
                bluetoothViewModel.sendMouseScroll(amount)
            }
            touchpadController.start()
        } else {
            touchpadController.stop()
            if (bluetoothViewModel.mouseControlMode.value == MouseControlMode.TOUCHPAD) {
                bluetoothViewModel.setMouseControlMode(MouseControlMode.NONE)
            }
        }
    }
    
    LaunchedEffect(isTouchpadActive) {
        if (isTouchpadActive) {
            scrollState.animateScrollTo(scrollState.maxValue)
        }
    }

    LaunchedEffect(isKeyboardActive) {
        if (isKeyboardActive) {
            focusRequester.requestFocus()
        }
    }
    
    // 当键盘收起时，自动取消键盘激活状态
    LaunchedEffect(isKeyboardVisible) {
        if (!isKeyboardVisible && isKeyboardActive) {
            selectedIndex = -1
        }
    }

    // 连接失败对话框
    if (errorMessage != null) {
        AlertDialog(
            onDismissRequest = { bluetoothViewModel.clearErrorMessage() },
            title = { Text(stringResource(id = R.string.connection_failed)) },
            text = { Text(errorMessage!!) },
            confirmButton = {
                TextButton(onClick = { bluetoothViewModel.clearErrorMessage() }) {
                    Text(stringResource(R.string.confirm_button))
                }
            }
        )
    }

    Box(modifier = Modifier
        .fillMaxSize()
        .background(MaterialTheme.colorScheme.background) // 添加背景色
        .navigationBarsPadding()) {
        Popup(
            alignment = Alignment.TopCenter,
            onDismissRequest = { /* ... */ }
        ) {
            // 为 Popup 的容器移除所有阴影
            Surface(
                modifier = Modifier.padding(top = 16.dp),
                color = Color.Transparent, // 背景交给内部组件处理，自身透明
                tonalElevation = 0.dp,
                shadowElevation = 0.dp
            ) {
                SplitButton(
                    bluetoothState = bluetoothState,
                    connectedDeviceName = connectedDeviceName,
                    availableDevices = availableDevices,
                    onScanDevices = { coroutineScope.launch { bluetoothViewModel.scanDevices() } },
                    onDeviceClick = { device -> coroutineScope.launch { bluetoothViewModel.connectToDevice(device) } }
                )
            }
        }

        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(scrollState)
                .padding(horizontal = 16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(modifier = Modifier.height(128.dp)) // 为顶部的SplitButton留出空间

            // 移除动态的weight Spacer，确保布局固定
            if (!isTouchpadActive) {
                Spacer(modifier = Modifier.weight(1f))
            }

            // 电源按钮 (警示色，保持不变)
            IconButton(
                onClick = { bluetoothViewModel.sendPowerKey() },
                modifier = Modifier.size(56.dp),
                colors = IconButtonDefaults.iconButtonColors(
                    containerColor = MaterialTheme.colorScheme.errorContainer,
                    contentColor = MaterialTheme.colorScheme.onErrorContainer
                )
            ) {
                Icon(
                    imageVector = ImageVector.vectorResource(id = R.drawable.ic_power_settings_new),
                    contentDescription = stringResource(id = R.string.power_button_description),
                    modifier = Modifier.size(24.dp)
                )
            }

            // 方向键圆环
            DirectionalPad(bluetoothViewModel = bluetoothViewModel)

            // Home, Mic, Back 按钮
            ActionButtonsRow1(bluetoothViewModel = bluetoothViewModel)

            // 音量控制按钮
            VolumeControlRow(bluetoothViewModel = bluetoothViewModel)

            // 模式切换按钮
            ConnectedModeButtons(
                selectedIndex = selectedIndex,
                onSelectedIndexChange = { selectedIndex = it }
            )

            Spacer(modifier = Modifier.height(32.dp)) // 按钮组下方的固定间距

             if (isTouchpadActive) {
                  Column(horizontalAlignment = Alignment.CenterHorizontally) {
                      // 触摸板UI
                      TouchpadView(
                          controller = touchpadController,
                          modifier = Modifier.padding(horizontal = 16.dp)
                      )
                     // 不需要额外的Trackpad组件
                      Spacer(modifier = Modifier.height(16.dp))
                     Spacer(modifier = Modifier.height(8.dp))  // 触摸板下方的间距
                 }
             }
             
             if (isKeyboardActive) {
                     var inputText by remember { mutableStateOf("") }
                     BasicTextField(
                         value = inputText,
                         onValueChange = { newValue ->
                             if (newValue.length > inputText.length) { // Character added
                                 val newChar = newValue.last()
                                 if (newChar.isAscii()) {
                                     bluetoothViewModel.sendAsciiKeyPress(newChar)
                                 } else {
                                     Toast.makeText(context, "Unsupported character", Toast.LENGTH_SHORT).show()
                                 }
                             }
                             inputText = newValue // Update the state
                         },
                         modifier = Modifier
                             .fillMaxWidth()
                             .height(0.dp)
                             .focusRequester(focusRequester)
                             .onKeyEvent { event ->
                                 if (event.type == KeyEventType.KeyUp) {
                                     when (event.key) {
                                         Key.Backspace -> bluetoothViewModel.sendBackspace()
                                         Key.Enter -> bluetoothViewModel.sendEnter()
                                     }
                                 }
                                 true
                             },
                         keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Default),
                     )
                 }
        }
    }
}

@Composable
fun SplitButton(
    bluetoothState: BluetoothConnectionState,
    connectedDeviceName: String,
    availableDevices: List<BluetoothDeviceInfo>,
    onScanDevices: () -> Unit,
    onDeviceClick: (BluetoothDeviceInfo) -> Unit
) {
    var expanded by remember { mutableStateOf(false) }
    val buttonColors = ButtonDefaults.buttonColors(
        containerColor = MaterialTheme.colorScheme.primary,
        contentColor = MaterialTheme.colorScheme.onPrimary
    )
    // 按钮高度为56dp，因此完美的半圆角半径为 28.dp
    val fullRadius = 28.dp
    val innerRadius = 4.dp

    Row(
        horizontalArrangement = Arrangement.spacedBy(2.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // --- 左侧按钮 ---
        Button(
            onClick = { /*TODO: 主操作*/ },
            modifier = Modifier
                .height(56.dp)
                .widthIn(max = 200.dp),
            shape = RoundedCornerShape(
                topStart = fullRadius, // 左上角为半圆
                bottomStart = fullRadius, // 左下角为半圆
                topEnd = innerRadius, // 右上角为内侧圆角
                bottomEnd = innerRadius  // 右下角为内侧圆角
            ),
            colors = buttonColors,
            elevation = ButtonDefaults.buttonElevation(0.dp),
            contentPadding = PaddingValues(start = 20.dp, end = 16.dp)
        ) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                // 根据连接状态显示不同的蓝牙图标
                val bluetoothIcon = when (bluetoothState) {
                    BluetoothConnectionState.CONNECTED -> R.drawable.ic_bluetooth_connected
                    else -> R.drawable.ic_bluetooth
                }
                Icon(
                    imageVector = ImageVector.vectorResource(id = bluetoothIcon),
                    contentDescription = stringResource(id = R.string.bluetooth_icon_description)
                )
                Spacer(modifier = Modifier.width(8.dp))
                
                // 根据连接状态显示不同的文本
                val displayText = when (bluetoothState) {
                    BluetoothConnectionState.DISCONNECTED -> stringResource(id = R.string.not_connected)
                    BluetoothConnectionState.SCANNING -> stringResource(id = R.string.scanning_devices)
                    BluetoothConnectionState.CONNECTING -> stringResource(id = R.string.connecting_to_device, connectedDeviceName)
                    BluetoothConnectionState.CONNECTED -> connectedDeviceName
                }
                Text(displayText)
            }
        }

        // --- 右侧按钮 ---
        Box {
            Button(
                onClick = {
                    expanded = true
                    // 无论当前状态如何，点击下拉按钮都立即开始扫描
                    onScanDevices()
                },
                modifier = Modifier.size(56.dp),
                shape = RoundedCornerShape(
                    topStart = innerRadius, // 左上角为内侧圆角
                    bottomStart = innerRadius, // 左下角为内侧圆角
                    topEnd = fullRadius, // 右上角为半圆
                    bottomEnd = fullRadius  // 右下角为半圆
                ),
                colors = buttonColors,
                elevation = ButtonDefaults.buttonElevation(0.dp),
                contentPadding = PaddingValues(0.dp)
            ) {
                Icon(
                    imageVector = ImageVector.vectorResource(id = R.drawable.ic_keyboard_arrow_down),
                    contentDescription = stringResource(id = R.string.open_device_list_button_description)
                )
            }
            
            // 下拉菜单
            DropdownMenu(
                expanded = expanded,
                onDismissRequest = { expanded = false }
            ) {
                // 显示设备列表，同时显示扫描状态
                // 先显示已配对设备，再显示未配对设备
                val pairedDevices = availableDevices.filter { it.isPaired }
                val unpaired = availableDevices.filter { !it.isPaired }
                
                // 显示已配对设备
                if (pairedDevices.isNotEmpty()) {
                    DropdownMenuItem(
                        text = { 
                            Text(
                                stringResource(id = R.string.paired_devices),
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.primary
                            ) 
                        },
                        onClick = { },
                        enabled = false
                    )
                    
                    pairedDevices.forEach { device ->
                        val isConnected = bluetoothState == BluetoothConnectionState.CONNECTED && 
                                         connectedDeviceName == device.name
                        DropdownMenuItem(
                            text = {
                                Row(verticalAlignment = Alignment.CenterVertically) {
                                    Text(
                                        text = device.name,
                                        // 如果当前已连接此设备，高亮显示
                                        color = if (isConnected) 
                                            MaterialTheme.colorScheme.primary 
                                        else 
                                            MaterialTheme.colorScheme.onSurface
                                    )
                                }
                            },
                            onClick = { onDeviceClick(device) }
                        )
                    }
                }
                
                // 显示未配对设备
                if (unpaired.isNotEmpty()) {
                    DropdownMenuItem(
                        text = { 
                            Text(
                                stringResource(id = R.string.available_devices),
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.primary
                            ) 
                        },
                        onClick = { },
                        enabled = false
                    )
                    
                    unpaired.forEach { device ->
                        val isConnected = bluetoothState == BluetoothConnectionState.CONNECTED && 
                                         connectedDeviceName == device.name
                        DropdownMenuItem(
                            text = {
                                Row(verticalAlignment = Alignment.CenterVertically) {
                                    Text(
                                        text = device.name,
                                        // 如果当前已连接此设备，高亮显示
                                        color = if (isConnected) 
                                            MaterialTheme.colorScheme.primary 
                                        else 
                                            MaterialTheme.colorScheme.onSurface
                                    )
                                }
                            },
                            onClick = { onDeviceClick(device) }
                        )
                    }
                }
                
                // 显示扫描状态
                if (bluetoothState == BluetoothConnectionState.SCANNING) {
                    DropdownMenuItem(
                        text = { 
                            Row(verticalAlignment = Alignment.CenterVertically) {
                                CircularProgressIndicator(modifier = Modifier.size(16.dp))
                                Spacer(modifier = Modifier.width(8.dp))
                                Text(stringResource(id = R.string.scanning_devices))
                            }
                        }, 
                        onClick = { },
                        enabled = false
                    )
                }
                
                // 如果没有设备且不在扫描中
                if (availableDevices.isEmpty() && bluetoothState != BluetoothConnectionState.SCANNING) {
                    DropdownMenuItem(
                        text = { Text(stringResource(id = R.string.no_devices_found)) }, 
                        onClick = { },
                        enabled = false
                    )
                }
            }
        }
    }
}

@Composable
fun DirectionalPad(bluetoothViewModel: BluetoothViewModel) {
    Box(
        modifier = Modifier
            .padding(top = 44.dp)
            .size(192.dp),
        contentAlignment = Alignment.Center
    ) {
        // 圆环背景
        Surface(
            shape = CircleShape,
            color = MaterialTheme.colorScheme.primaryContainer, // 更新颜色
            modifier = Modifier.fillMaxSize()
        ) {}

        // 中心带边框的圆形
        Box(
            modifier = Modifier.size(82.dp),
            contentAlignment = Alignment.Center
        ) {
            IconButton(
                onClick = { bluetoothViewModel.sendOkKey() },
                modifier = Modifier
                    .size(82.dp)
                    .border(1.dp, MaterialTheme.colorScheme.primary, CircleShape),
                colors = IconButtonDefaults.iconButtonColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    contentColor = MaterialTheme.colorScheme.onPrimaryContainer // 确保内容颜色与背景对比
                )
            ) {
                // 不放置任何图标，保持为空以实现只显示边框的效果
            }
        }

        val iconColor = MaterialTheme.colorScheme.onPrimaryContainer // 图标颜色

        // 方向按钮
        IconButtonInPad(bluetoothViewModel, Alignment.TopCenter, R.drawable.ic_keyboard_arrow_up, stringResource(id = R.string.direction_up), iconColor, ConsumerControlCode.UP)
        IconButtonInPad(bluetoothViewModel, Alignment.CenterEnd, R.drawable.ic_keyboard_arrow_right, stringResource(id = R.string.direction_right), iconColor, ConsumerControlCode.RIGHT)
        IconButtonInPad(bluetoothViewModel, Alignment.BottomCenter, R.drawable.ic_keyboard_arrow_down, stringResource(id = R.string.direction_down), iconColor, ConsumerControlCode.DOWN)
        IconButtonInPad(bluetoothViewModel, Alignment.CenterStart, R.drawable.ic_keyboard_arrow_left, stringResource(id = R.string.direction_left), iconColor, ConsumerControlCode.LEFT)
    }
}

@Composable
fun BoxScope.IconButtonInPad(bluetoothViewModel: BluetoothViewModel, alignment: Alignment, iconRes: Int, contentDescription: String, tint: Color, consumerControlCode: ConsumerControlCode) {
    IconButton(
        onClick = { bluetoothViewModel.sendDpad(consumerControlCode) },
        modifier = Modifier.align(alignment).size(56.dp)
    ) {
        Icon(
            imageVector = ImageVector.vectorResource(id = iconRes),
            contentDescription = contentDescription,
            modifier = Modifier.size(24.dp),
            tint = tint
        )
    }
}

@Composable
fun ActionButtonsRow1(bluetoothViewModel: BluetoothViewModel) {
    Row(
        modifier = Modifier.padding(top = 44.dp),
        horizontalArrangement = Arrangement.spacedBy(44.dp, Alignment.CenterHorizontally),
        verticalAlignment = Alignment.CenterVertically
    ) {
        ThemedIconButton(iconRes = R.drawable.ic_home, contentDescription = stringResource(id = R.string.home_button_description), onClick = { bluetoothViewModel.sendHomeKey() })
        ThemedIconButton(iconRes = R.drawable.ic_mic, contentDescription = stringResource(id = R.string.microphone_button_description), onClick = { bluetoothViewModel.sendVoiceAssistant() })
        ThemedIconButton(iconRes = R.drawable.ic_undo, contentDescription = stringResource(id = R.string.back_button_description), onClick = { bluetoothViewModel.sendBackKey() })
    }
}

@Composable
fun VolumeControlRow(bluetoothViewModel: BluetoothViewModel) {
    Row(
        modifier = Modifier.padding(top = 44.dp),
        horizontalArrangement = Arrangement.spacedBy(44.dp, Alignment.CenterHorizontally),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 音量加减胶囊
        Surface(
            modifier = Modifier.size(width = 156.dp, height = 56.dp),
            shape = CircleShape,
            color = MaterialTheme.colorScheme.primaryContainer
        ) {
            Row(
                modifier = Modifier.fillMaxSize(),
                // SpaceBetween 将子项推向两端，实现紧贴边缘的效果
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 左按钮 (Volume Down)
                IconButton(
                    onClick = { bluetoothViewModel.sendVolumeDown() },
                    // 按钮尺寸与 ThemedIconButton 保持一致，确保对齐
                    modifier = Modifier.size(56.dp)
                ) {
                    Icon(
                        imageVector = ImageVector.vectorResource(id = R.drawable.ic_volume_down),
                        contentDescription = stringResource(id = R.string.volume_down_button_description),
                        modifier = Modifier.size(24.dp),
                        // 使用与 ThemedIconButton 相同的图标颜色，保证风格统一
                        tint = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                }
                // 右按钮 (Volume Up)
                IconButton(
                    onClick = { bluetoothViewModel.sendVolumeUp() },
                    modifier = Modifier.size(56.dp)
                ) {
                    Icon(
                        imageVector = ImageVector.vectorResource(id = R.drawable.ic_volume_up),
                        contentDescription = stringResource(id = R.string.volume_up_button_description),
                        modifier = Modifier.size(24.dp),
                        tint = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                }
            }
        }

        // 静音按钮
        ThemedIconButton(iconRes = R.drawable.ic_volume_off, contentDescription = stringResource(id = R.string.mute_button_description),onClick = { bluetoothViewModel.sendMute() })
    }
}

@Composable
fun Trackpad() {
    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp) // 16dp (Column) + 16dp (this) = 32dp from screen edge
            .aspectRatio(3f / 2f),
        shape = RoundedCornerShape(4.dp),
        color = MaterialTheme.colorScheme.primaryContainer
    ) {
        // The trackpad area is intentionally left blank for now.
    }
}

@Composable
fun ConnectedModeButtons(
    selectedIndex: Int,
    onSelectedIndexChange: (Int) -> Unit
) {
    // var selectedIndex by remember { mutableIntStateOf(-1) } // 默认全部处于未激活状态
    val icons = listOf(
        R.drawable.ic_mouse,
        R.drawable.ic_trackpad_input,
        R.drawable.ic_keyboard_alt
    )
    val descriptions = listOf(stringResource(id = R.string.mouse_button_description), stringResource(id = R.string.trackpad_button_description), stringResource(id = R.string.keyboard_button_description))

    val buttonHeight = 32.dp
    val fullRadius = buttonHeight / 2
    val innerRadius = 4.dp

    Row(
        modifier = Modifier.padding(top = 44.dp),
        horizontalArrangement = Arrangement.spacedBy(2.dp), // 设置按钮间距为 2dp
        verticalAlignment = Alignment.CenterVertically
    ) {
        icons.forEachIndexed { index, icon ->
            val isActive = selectedIndex == index

            val containerColor by animateColorAsState(
                targetValue = if (isActive) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.primaryContainer,
                animationSpec = tween(durationMillis = 200),
                label = "containerColorAnimation"
            )
            val contentColor by animateColorAsState(
                targetValue = if (isActive) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onPrimaryContainer,
                animationSpec = tween(durationMillis = 200),
                label = "contentColorAnimation"
            )

            val topStartRadius by animateDpAsState(
                targetValue = if (isActive || index == 0) fullRadius else innerRadius,
                animationSpec = tween(durationMillis = 200),
                label = "topStartRadiusAnimation"
            )
            val bottomStartRadius by animateDpAsState(
                targetValue = if (isActive || index == 0) fullRadius else innerRadius,
                animationSpec = tween(durationMillis = 200),
                label = "bottomStartRadiusAnimation"
            )
            val topEndRadius by animateDpAsState(
                targetValue = if (isActive || index == icons.lastIndex) fullRadius else innerRadius,
                animationSpec = tween(durationMillis = 200),
                label = "topEndRadiusAnimation"
            )
            val bottomEndRadius by animateDpAsState(
                targetValue = if (isActive || index == icons.lastIndex) fullRadius else innerRadius,
                animationSpec = tween(durationMillis = 200),
                label = "bottomEndRadiusAnimation"
            )

            TextButton(
                onClick = {
                    val newIndex = if (isActive) -1 else index
                    onSelectedIndexChange(newIndex)
                },
                modifier = Modifier
                    .width(84.dp)   // 每个按钮固定宽度
                    .height(buttonHeight), // 标准 XSmall 高度
                shape = RoundedCornerShape(
                    topStart = topStartRadius,
                    bottomStart = bottomStartRadius,
                    topEnd = topEndRadius,
                    bottomEnd = bottomEndRadius
                ),
                colors = ButtonDefaults.textButtonColors(
                    containerColor = containerColor,
                    contentColor = contentColor
                ),
                contentPadding = PaddingValues(0.dp)
            ) {
                Icon(
                    imageVector = ImageVector.vectorResource(id = icon),
                    contentDescription = descriptions[index],
                    modifier = Modifier.size(20.dp)
                )
            }
        }
    }
}


@Composable
fun ThemedIconButton(
    iconRes: Int,
    contentDescription: String,
    onClick: () -> Unit // 1. 添加 onClick 参数
) {
    IconButton(
        onClick = onClick, // 2. 将参数传递给内部的 IconButton
        modifier = Modifier.size(56.dp),
        colors = IconButtonDefaults.iconButtonColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer,
            contentColor = MaterialTheme.colorScheme.onPrimaryContainer
        )
    ) {
        Icon(
            imageVector = ImageVector.vectorResource(id = iconRes),
            contentDescription = contentDescription,
            modifier = Modifier.size(24.dp)
        )
    }
}


private fun Char.isAscii(): Boolean {
    return this.code in 0..127
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    // 确保你的主题已正确设置
    BluetoothRemoteControlTheme {
        RemoteControlScreen(bluetoothService = null)
    }
}

